<template>
  <div class="monthlySummary">
    <DFPageList ref="dfPageListRef" :page-options="pageOptions">
      <template #list>
        <div class="list-view">
          <div class="page-list">
            <div class="page-list__head">
              <div class="head-left">
                {{ $t('monthlySummary.table.overallMachinePerformance') }}
              </div>
            </div>
            <div class="page-list__body">
              <n-descriptions
                :label-style="labelStyle"
                label-placement="left"
                label-align="right"
                bordered
                :column="3"
                :content-style="{
                  verticalAlign: 'middle',
                }"
              >
                <template v-for="item in descriptionsItem">
                  <n-descriptions-item :label="t(`monthlySummary.table.${item.label}`)">{{
                    [null, undefined].includes(item.value) ? '-' : item.value
                  }}</n-descriptions-item>
                </template>
              </n-descriptions>
            </div>
          </div>
          <div class="page-list">
            <n-grid cols="2" item-responsive responsive="self" :x-gap="30" :y-gap="10">
              <n-grid-item span="2 400:2 600:2 800:1">
                <div class="page-list__head">
                  <div class="head-left">
                    {{ $t('monthlySummary.table.defectPhenomenonAnalysis') }}
                  </div>
                </div>
                <div class="page-list__body">
                  <DFTable
                    ref="defectPhenomenonTableRef"
                    noDefaultLoad
                    :columns="defectPhenomenonTableColumns"
                    :row-key="(row) => row.id"
                    :min-height="240"
                  />
                </div>
              </n-grid-item>
              <n-grid-item span="2 400:2 600:2 800:1">
                <div class="page-list__head">
                  <div class="head-left">
                    {{ $t('monthlySummary.table.downtimeReasonAnalysis') }}
                  </div>
                </div>
                <div class="page-list__body">
                  <DFTable
                    ref="downtimeReasonsTableRef"
                    noDefaultLoad
                    :columns="downtimeReasonsTableColumns"
                    :row-key="(row) => row.id"
                    :min-height="240"
                  />
                </div>
              </n-grid-item>
            </n-grid>
          </div>
          <div class="page-list">
            <div class="page-list__head">
              <div class="head-left">
                {{ $t('monthlySummary.table.corrugatedTypeAnalysis') }}
              </div>
            </div>
            <div class="page-list__body">
              <DFTable
                ref="corrugatedTypeTableRef"
                noDefaultLoad
                :columns="corrugatedTypeTableColumns"
                :row-key="(row) => row.id"
                :min-height="240"
              />
            </div>
          </div>
        </div>
      </template>
    </DFPageList>
  </div>
</template>

<script setup lang="ts">
  import { DFTable } from '@/components/DFTable';
  import { useMixins } from '@/hooks/useMixins';
  import lang from './lang';
  import { listMachine } from '@/api/base/machine';
  import { listShift } from '@/api/base/shift';
  import { listMonthlySummary } from '@/api/reportForm/monthlySummary';

  const dfPageListRef = ref(null);

  const defectPhenomenonTableRef: any = ref(null);

  const downtimeReasonsTableRef: any = ref(null);

  const corrugatedTypeTableRef: any = ref(null);

  const { loadLangFn, t } = useMixins();

  loadLangFn(lang);

  const labelStyle = ref({ width: '150px' });

  const descriptionsItem: any = ref([
    {
      label: 'machineName',
      value: '',
    },
    {
      label: 'avgTestingTime',
      value: '',
    },
    {
      label: 'totalPowerConsumption',
      value: '',
    },
    {
      label: 'shiftName',
      value: '',
    },
    {
      label: 'avgSpeed',
      value: '',
    },
    {
      label: 'totalElectricityCost',
      value: '',
    },
    {
      label: 'totalWorkingDays',
      value: '',
    },
    {
      label: 'totalCompletedWO',
      value: '',
    },
    {
      label: 'totalWaterConsumption',
      value: '',
    },
    {
      label: 'totalWorkingTime',
      value: '',
    },
    {
      label: 'totalCompletedQTY',
      value: '',
    },
    {
      label: 'totalWaterCost',
      value: '',
    },
    {
      label: 'totalProductionTime',
      value: '',
    },
    {
      label: 'totalYieldQTY',
      value: '',
    },
    {
      label: 'totalInkConsumption',
      value: '',
    },
    {
      label: 'totalTestingTime',
      value: '',
    },
    {
      label: 'totalYieldRate',
      value: '',
    },
    {
      label: 'totalInkCost',
      value: '',
    },
    {
      label: 'totalDowntimeDurationH',
      value: '',
    },
    {
      label: 'totalYieldArea',
      value: '',
    },
    {
      label: 'totalLaborCosts',
      value: '',
    },
    {
      label: 'totalEffectiveProductionTime',
      value: '',
    },
    {
      label: 'totalYieldValue',
      value: '',
    },
    {
      label: 'totalProductionCost',
      value: '',
    },
  ]);

  const machineList: any = ref([]);

  const shiftList: any = ref([]);

  const defectPhenomenonTableColumns = [
    // {
    //   width: 60,
    //   fixed: 'left',
    // },
    { label: 'defectPhenomenon', key: 'badName' },
    { label: 'totalQTY', key: 'badNum' },
    { label: 'ratio', key: 'badRate' },
  ];

  const downtimeReasonsTableColumns = [
    // {
    //   width: 60,
    //   fixed: 'left',
    // },
    { label: 'downtimeReasons', key: 'shutdownReasonName' },
    { label: 'totalDowntimeDurationM', key: 'shutdownDuration' },
    { label: 'ratio', key: 'shutdownRate' },
  ];

  const corrugatedTypeTableColumns = [
    // {
    //   width: 60,
    //   fixed: 'left',
    // },
    { label: 'flute', key: 'corrugatedTypeName' },
    { label: 'totalCardboardQTY', key: 'paperboardNum' },
    { label: 'ratio', key: 'paperboardRate' },
    { label: 'totalCardBoardArea', key: 'totalCardBoardArea' },
    { label: 'ratio', key: 'totalCardBoardAreaRate' },
  ];

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'machineName',
          prop: 'machineCode',
          component: 'NSelect',
          options: machineList,
        },
        {
          label: 'shiftName',
          prop: 'shiftCode',
          component: 'NSelect',
          options: shiftList,
        },
        {
          label: 'month',
          component: 'NDatePicker',
          defaultValue: null,
          componentProps: {
            clearable: false,
            type: 'month',
            // valueFormat: 'y年 M月',
            // yearFormat: 'y年',
            // monthFormat: 'M月',
            // onUpdateValue: (_, v: string[]) => {
            //   if (v) {
            //     // scheduledStartTime.value.createStartTime = v[0];
            //     // scheduledStartTime.value.createEndTime = v[1];
            //   } else {
            //     // scheduledStartTime.value.createStartTime = '';
            //     // scheduledStartTime.value.createEndTime = '';
            //   }
            // },
          },
        },
      ],
      // beforeResetFn: () => {
      //   dfPageListRef?.value?.setQueryFormFieldsValueFn({
      //     machineCode: machineList.value[0]?.value,
      //     shiftCode: shiftList.value[0]?.value,
      //     month: new Date().getTime(),
      //   });
      // },
      //   requestFn: (data) => {
      //     const newData = setRequestDataFn(data);
      //     console.log(newData);
      //   },
      requestFn: async (arg) => {
        const { entity } = arg;

        if (!entity.month) {
          entity.month = new Date().getTime();

          dfPageListRef?.value?.setQueryFormFieldsValueFn({
            month: entity.month,
          });
        }

        if (!entity.machineCode) {
          entity.machineCode = machineList.value[0]?.value;
          dfPageListRef?.value?.setQueryFormFieldsValueFn({
            machineCode: entity.machineCode,
          });
        }

        if (!entity.shiftCode) {
          entity.shiftCode = shiftList.value[0]?.value;
          dfPageListRef?.value?.setQueryFormFieldsValueFn({
            shiftCode: entity.shiftCode,
          });
        }

        const { data } = await listMonthlySummary(arg);

        if (data) {
          const {
            comprehenPerformance,
            reportMonthComprehensiveBadList,
            reportMonthComprehensiveCorrugatedList,
            reportMonthComprehensiveDownList,
          } = data;

          for (const item of descriptionsItem.value) {
            item.value = comprehenPerformance[item.label];
          }

          nextTick(() => {
            defectPhenomenonTableRef.value?.setTableData(reportMonthComprehensiveBadList);

            downtimeReasonsTableRef.value?.setTableData(reportMonthComprehensiveDownList);

            corrugatedTypeTableRef.value?.setTableData(reportMonthComprehensiveCorrugatedList);
          });
        } else {
          for (const item of descriptionsItem.value) {
            item.value = null;
          }

          nextTick(() => {
            defectPhenomenonTableRef.value?.setTableData([]);

            downtimeReasonsTableRef.value?.setTableData([]);

            corrugatedTypeTableRef.value?.setTableData([]);
          });
        }
      },
    },
    table: {
      noTable: true,
      afterSlotName: 'list',
    },
  };

  const initDictData = async () => {
    const res = await Promise.all([listMachine(), listShift()]);

    const [list1, list2] = res;

    machineList.value =
      list1?.data.map((item) => ({ label: item.machineName, value: item.machineCode })) || [];

    shiftList.value =
      list2?.data.map((item) => ({
        label: item.shiftName,
        value: item.shiftCode,
      })) || [];

    nextTick(() => {
      dfPageListRef?.value?.setQueryFormFieldsValueFn({
        machineCode: machineList.value[0]?.value,
        shiftCode: shiftList.value[0]?.value,
        month: new Date().getTime(),
      });

      setTimeout(() => {
        nextTick(() => {
          dfPageListRef?.value?.reloadTableFn(false);
        });
      }, 300);
    });
  };

  initDictData();
</script>

<style lang="less" scoped>
  .monthlySummary {
    .list-view {
      width: 100%;
    }
    .page-list {
      margin-top: 16px;
      border-radius: 2px;
      // padding: 24px 24px 48px;
      background: #fff;
      &__head {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 44px;
        .head-left {
          font-size: 16px;
          font-weight: 500;
          color: #222;
        }
      }
    }
  }
</style>
